package com.hw.protocol.tool.decode.hw;

import com.hw.protocol.tool.model.entity.hw.RegulatorBox;
import com.hw.protocol.tool.util.CrcUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;

/**
 * @author : lihy
 * @date : 2023/10/19 10:45
 * description: 智能调压箱数据解码器
 */
@Slf4j
public class RegulatorBoxDecode {

    private RegulatorBox box;

    ByteBuf dataBuf;

    public RegulatorBoxDecode(RegulatorBox box, byte[] data) {
        this.box = box;
        this.dataBuf = Unpooled.wrappedBuffer(data);
    }

    public boolean buildObject() {
        if (crc()) {
            int crc = dataBuf.readShort();
            byte[] noCrc = new byte[dataBuf.capacity() - 2];
            dataBuf.getBytes(0, noCrc);
            int calCrc = CrcUtil.getCrcInteger(noCrc, true);
            if (crc != calCrc) {
                byte[] allBytes = new byte[dataBuf.capacity()];
                dataBuf.getBytes(0, allBytes);
                log.error("数据校验失败，原始数据:[{}]", allBytes);
                return false;
            }
        }
        box.setMeterType(dataBuf.readShortLE());
        box.setInPress(dataBuf.readFloatLE());
        box.setOutPress(dataBuf.readFloatLE());
        box.setTemperature(dataBuf.readFloatLE());
        box.setDifferentialPressure1(dataBuf.readFloatLE());
        box.setDifferentialPressure2(dataBuf.readFloatLE());
        box.setLeakage(dataBuf.readFloatLE());
        box.setValveOpening1((char) dataBuf.readByte());
        box.setValveOpening2((char) dataBuf.readByte());
        box.setValveSsv1((char) dataBuf.readByte());
        box.setValveSsv2((char) dataBuf.readByte());
        box.setDoorSignal1((char) dataBuf.readByte());
        box.setDoorSignal2((char) dataBuf.readByte());
        byte[] flag = new byte[4];
        dataBuf.getBytes(dataBuf.capacity() - 4, flag);
        box.setFlag(flag);

        dataBuf.release();
        return true;
    }

    boolean crc() {
        return false;
    }
}
